#include <iostream>
#include <string>
#include <cstdlib>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include "common_gestor_envios.h"
#define TAM_BUFFER 100

using std::size_t;
using std::string;
using std::cout;
using std::endl;

Gestor_envios::Gestor_envios(){
}

Gestor_envios::~Gestor_envios(){
}

bool Gestor_envios::buscar_fin_de_linea(char* buffer){
	if (strstr(buffer, "\n") != NULL){
		return true;
	}	
	return false;		
}	

int Gestor_envios::agrandar_buffer(char* buffer, int buffer_tam){
	int tam = strlen(buffer) * 2;//
	char* aux = (char*)malloc(tam * sizeof(char));
	strncpy(aux, buffer, buffer_tam);
	aux[buffer_tam] = '\0';
	char* aux_buffer = buffer;
	buffer = aux;
	free(aux_buffer);
	return tam;
}

int Gestor_envios::enviar(int aux_fd, string buffer, int tam){
	unsigned int enviados = 0; 					//cantidad de bytes ya enviados.
	//int falta_enviar = buffer.size; 	//cantidad de bytes que faltan enviar.
        int falta_enviar = tam;                 //cantidad de bytes que faltan enviar.
	int n;
	const char* aux = buffer.c_str();
	while(enviados < buffer.size()) {
		n = send(aux_fd, aux+enviados, falta_enviar, 0);
		if (n == -1){	
			return -1;
		}	
		enviados += n;
		falta_enviar -= n;
	}
	return 0;
}

int Gestor_envios::recibir(int aux_fd, string* buffer, int tam){
	int numbytes;
	//int tam_buffer = TAM_BUFFER;
        int tam_buffer = tam;
	char* aux = (char*)malloc(tam_buffer * sizeof(char));
	if ((numbytes = recv(aux_fd, aux, tam_buffer, 0)) == -1){
		free(aux);
		return -1;
	}
	int cant_agregada;
	while (buscar_fin_de_linea(aux) == false){
		int pos = numbytes;
		tam_buffer = agrandar_buffer(aux, numbytes);//
		if ((cant_agregada = recv(aux_fd, aux+pos, tam_buffer-pos, 0)) == -1){
			free(aux);
			return -1;
		}
		numbytes += cant_agregada;
	}
	aux[numbytes] = '\0';
	*buffer = string(aux);
	free(aux);
	return numbytes;	
}
